<template>
	<view>
		<view class="news-details" style="padding: 0 20rpx;">

			<view class="main" :user-select="true">
				<u-parse :selectable="true" ref="article" :user-select="true" :html="article_content" />

			</view>
		</view>
		<view class="float-tab ~column">
			<button class="downBtn" @click="copyText">
				<text class="xs">复制文本</text>
			</button>
			<button class="downBtn" @click="copyImg">
				<text class="xs">下载图片</text>
			</button>
			<button class="downBtn" @click="copyVideo">
				<text class="xs">下载视频</text>
			</button>
			<button class="downBtn" open-type="share">
				<text class="xs">分享</text>
			</button>

		</view>
		<loading-view v-if="showLoading"></loading-view>
	</view>
</template>

<script>
	import {
		getArticleDetail,
		getSourceDetail
	} from '@/api/store';
	import {
		SID
	} from '@/config/cachekey';
	import Cache from '@/utils/cache'
	import {
		getRect
	} from "@/utils/tools"
	import {
		writePhotosAlbum,
	} from '@/utils/writePhotosAlbum.js'

	export default {
		data() {
			return {
				showLoading: true,
				articleDetail: {},
				article_content: "",
				top: 0,
				noteImageList: [],
				noteText: '',
				allVideos: []
			};
		},

		components: {},
		props: {},

		/**
		 * 生命周期函数--监听页面加载
		 */
		onLoad() {
			const options=this.$Route.query
			this.id = options.id
			this.getArticleDetailFun();
			const noteContent = this.$refs.article
			this.noteImageList = noteContent.imgList
		},
		onShow() {
			uni.hideHomeButton()
			getRect(".tab-img", false, this).then(res => {
				this.height = res.height
			});
		},
		async onShareAppMessage() {
			const {
				articleDetail,
			} = this;
			return {
				title: articleDetail.code,
				imageUrl: articleDetail.image,
				path: 'bundle_b/pages/note_detail/note_detail?id=' + articleDetail.id + "&sid=" +  articleDetail.shop_id,
			};
		},
		methods: {
			getArticleDetailFun() {
				getSourceDetail({
					id: this.id,
					sid: Cache.get(SID) || 1
				}).then(res => {
					if (res.code == 1) {
						this.articleDetail = res.data
						setTimeout(() => {
							this.article_content = res.data.content;
							this.noteText = this.getText(this.article_content)
							this.allVideos = this.parseVideo(this.article_content)
						}, 200);
						setTimeout(() => {
							this.showLoading = false
						}, 300);

					}
				});
			},
			shareNote(){
				
			},
			//一键复制文本
			copyText() {
				let text = this.noteText
				wx.setClipboardData({ //复制文本
					data: text,
					success: function(res) {
						wx.getClipboardData({ //获取复制文本
							success: function(res) {
								wx.showToast({
									title: '复制成功',
									icon: "none", //是否需要icon
									mask: "true" //是否设置点击蒙版，防止点击穿透
								})
							}
						})
					}
				})
			},
			// 一键保存图片到本地
			copyImg() {

				var _this = this
				// 获取保存到相册权限
				writePhotosAlbum(
					function success() {
						wx.showLoading({
							title: '加载中',
							mask: true
						})
						// 调用保存图片promise队列
						let imagesArr = _this.noteImageList
						_this.queue(imagesArr)
							.then(res => {
								wx.hideLoading()
								wx.showToast({
									title: '保存成功'
								})
							})
							.catch(err => {
								wx.hideLoading()
								console.log(err)
							})
					},
					function fail() {
						wx.showToast({
							title: '您拒绝了保存到相册'
						})
					}
				)
			},
			// 队列
			queue(urls) {
				let promise = Promise.resolve()
				urls.forEach((url, index) => {
					promise = promise.then(() => {
						return this.download(url)
					})
				})
				return promise
			},
			// 下载
			download(url) {
				return new Promise((resolve, reject) => {
					wx.downloadFile({
						url: url,
						success: function(res) {
							var temp = res.tempFilePath
							wx.saveImageToPhotosAlbum({
								filePath: temp,
								success: function(res) {
									resolve(res)
								},
								fail: function(err) {
									reject(res)
								}
							})
						},
						fail: function(err) {
							reject(err)
						}
					})
				})
			},
			copyVideo() {
				var _this = this
				writePhotosAlbum(
					function success() {
						wx.showLoading({
							title: '加载中',
							mask: true
						})
						// 调用保存图片promise队列
						let imagesArr = _this.allVideos
						_this.queueV(imagesArr)
							.then(res => {
								wx.hideLoading()
								wx.showToast({
									title: '保存成功'
								})
							})
							.catch(err => {
								wx.hideLoading()
								console.log(err)
							})
					},
					function fail() {
						wx.showToast({
							title: '您拒绝了保存到相册'
						})
					}
				)
			},
			// 队列
			queueV(urls) {
				let promise = Promise.resolve()
				urls.forEach((url, index) => {
					promise = promise.then(() => {
						return this.downloadV(url)
					})
				})
				return promise
			},
			// 下载
			downloadV(url) {
				return new Promise((resolve, reject) => {
					wx.downloadFile({
						url: url,
						success: function(res) {
							var temp = res.tempFilePath
							wx.saveVideoToPhotosAlbum({
								filePath: temp,
								success: function(res) {
									resolve(res)
								},
								fail: function(err) {
									reject(res)
								}
							})
						},
						fail: function(err) {
							reject(err)
						}
					})
				})
			},
			getText(str) {
				return str
					.replace(/<[^<>]+>/g, "")
					.replace(/&nbsp;/gi, "");
			},
			parseVideo(richText) {
				//提取富文本视频链接
				
				let videoArr = []; //视频列表
				//通过 http + .mp4/.3gp/.m3u8识别视频链接
				let arr = richText.split('http');
				for (let i in arr) {
					let item = arr[i],
						urlMatch = null,
						mp4 = item.lastIndexOf(".mp4"),
						gp3 = item.lastIndexOf(".3gp"),
						m3u8 = item.lastIndexOf(".m3u8");
					if (mp4 > 0) {
						urlMatch = 'http' + item.substring(0, mp4) + ".mp4";
						videoArr.push(urlMatch);
					} else if (gp3 > 0) {
						urlMatch = 'http' + item.substring(0, gp3) + ".3gp";
						videoArr.push(urlMatch);
					} else if (m3u8 > 0) {
						urlMatch = 'http' + item.substring(0, m3u8) + ".m3u8";
						videoArr.push(urlMatch);
					}

				}
				//数组去重
				const videos = new Set(videoArr);
				return videos
			}

		}
	};
</script>
<style lang="scss">
	page {
		background-color: #fff;

	}

	.news-details .header {
		padding: 20rpx 15px;
		border-bottom: $-solid-border;
	}

	.news-details .main {}

	.float-tab {
		position: fixed;
		right: 16rpx;
		bottom: 280rpx;
		width: 116rpx;
		height: 96rpx;
		z-index: 777;

		.downBtn {
			background: #c5c5c5;
			margin-top: 10rpx;
			padding: 0 10rpx;
		}
	}
</style>